import numpy as np
import matplotlib.pyplot as plt
import os
import pandas as pd
import random
from extract_center import CenterExtracter
plt.rcdefaults()
plt.rcdefaults()
c = CenterExtracter()
x, y= (0,0)
h, w=(500,500)
img = c._read_image("34.jpg")
c.ref_image = "ref_image.jpg"
img = c._subtract_image(img)
img = c._threshold(image = img)
img = c._crop(img, x, y, h, w)
c._show_image(img)
ys1 = np.nonzero(img.argmax(axis=1))[0]
xs1 = np.nonzero(img.argmax(axis=0))[0]
xs2 = img.argmax(axis=1)[ys1]
ys2 = img.argmax(axis=0)[xs1]
ys1, ys2
xs1, xs2
plt.imshow(-img, cmap='gray')
plt.plot(xs1, ys2, 'ro')
plt.xlim([150, 200])
plt.ylim([110,75])
plt.imshow(-img, cmap='gray')
plt.plot(xs2, ys1, 'ro')
plt.xlim([150, 200])
plt.ylim([110,75])
xs = (np.concatenate((xs2, xs1), axis=0))
ys = (np.concatenate((ys1, ys2), axis=0))
plt.imshow(-img, cmap='gray')
plt.scatter(xs, ys)
plt.xlim([150, 200])
plt.ylim([110,75])
plt.plot(xs, ys, 'ro')
plt.figure(figsize=(10,10))
plt.subplot(2,2,1)
plt.imshow(-img, cmap='gray')
plt.plot(xs2, ys1, 'ro')
plt.xlim([150, 200])
plt.ylim([110,75])
plt.title("Looping through rows")
plt.subplot(2,2,2)
plt.imshow(-img, cmap='gray')
plt.plot(xs1, ys2, 'ro')
plt.xlim([150, 200])
plt.ylim([110,75])
plt.title("Looping through columns")
plt.subplot(2,2,3)
xs = (np.concatenate((xs2, xs1), axis=0))
ys = (np.concatenate((ys1, ys2), axis=0))
plt.imshow(-img, cmap='gray')
plt.scatter(xs, ys)
plt.xlim([150, 200])
plt.ylim([110,75])
plt.title("All points")
plt.subplot(2,2,4)
plt.scatter(xs, ys)
plt.xlim([150, 185])
plt.ylim([110,75])
plt.title("All points")
plt.savefig("all_points.png")
import numpy as np
from skimage.measure import EllipseModel
from matplotlib.patches import Ellipse
import matplotlib.pyplot as plt
points = np.array([xs, ys]).T
ell = EllipseModel()
ell.estimate(points)
xc, yc, a, b, theta = ell.params
print("center = ", (xc, yc))
print("angle of rotation = ", theta)
print("axes = ", (a,b))
fig, axs = plt.subplots(2, 1, sharex=True, sharey=True)
fig.set_size_inches(5, 10)
axs[0].scatter(xs,ys)
axs[1].scatter(xs, ys)
axs[1].scatter(xc, yc, color='red', s=100)
axs[0].set_title("All points")
# axs[1].set_xlim(xs.min(), xs.max())
# axs[1].set_ylim(ys.min(), ys.max())
ell_patch = Ellipse((xc, yc), 2*a, 2*b, theta*180/np.pi, edgecolor='red', facecolor='none')
axs[1].add_patch(ell_patch)
axs[1].set_title("Fitted Ellipse")
plt.show()
fig.savefig("ellipse_fit.png")
def all_points(image):
c = CenterExtracter()
x, y= (0,0)
h, w=(500,500)
img = c._read_image_(image)
img = c._subtract_image_(img)
img = c._threshold_(image = img)
img = c._crop_(img, x, y, h, w)
ys1 = np.nonzero(img.argmax(axis=1))[0]
xs1 = np.nonzero(img.argmax(axis=0))[0]
xs2 = img.argmax(axis=1)[ys1]
ys2 = img.argmax(axis=0)[xs1]
xs = (np.concatenate((xs2, xs1), axis=0))
ys = (np.concatenate((ys1, ys2), axis=0))
return xs, ys
def fit_ellipse(image, crop_included=True):
xs, ys = all_points(image)
points = np.array([xs, ys]).T
ell = EllipseModel()
ell.estimate(points)
xc, yc, a, b, theta = ell.params
if crop_included:
xc+=c.X
yc+=c.Y
return int(xc), int(yc), int(a), int(b), round(theta,2)
image = "../data/images1/12.jpg"
fit_ellipse(image)
image = "../data/images1/112.jpg"
fit_ellipse(image)
c = CenterExtracter()
imgs = os.listdir("../data/images1")
len(imgs)
sorted_images = sorted(imgs, key=lambda x: int(x.split(".")[0]))
img = "120.jpg"
img_path = "../data/images1"+f"/{img}"
c.fit_ellipse(img_path, )
xcs = []
ycs = []
r1s = []
r2s = []
thetas = []
for img in sorted_images:
img_path = "../data/images1"+f"/{img}"
try:
(xc, yc), (a, b), theta = c.fit_ellipse(img_path, plot=False)
xcs.append(xc)
ycs.append(yc)
r1s.append(a)
r2s.append(b)
thetas.append(theta)
except:
print(f"Error at: {img}")
xcs.append(None)
ycs.append(None)
r1s.append(None)
r2s.append(None)
thetas.append(None)
df = pd.DataFrame({"image": sorted_images, "x": xcs, "y": ycs, "r1": r1s, "r2": r2s, "theta":thetas})
df.head()
len_samples = 49
plt.figure(figsize=(30, 30))
df = df[df["x"].notna()]
samples = random.sample(list(df["image"][:-10]), len_samples)
for img in samples:
plt.subplot(7, 7, samples.index(img)+1)
x, y = df[df["image"] == img]["x"].values[0], df[df["image"] == img]["y"].values[0]
plt.imshow(plt.imread("../data/images1"+"/"+img)[200:, 500:], cmap="gray")
plt.hlines(y-200, 0, 1300-600, color="r")
plt.vlines(x-500, 0, 800-300, color="g")
plt.title(img)
plt.axis("off")
plt.tight_layout()
plt.annotate("Fitting Ellipse", (0, 0), (0, -30), xycoords='axes fraction', textcoords='offset points', va='top', fontsize=30)
plt.savefig("samples_with_ellipse.jpg")
df.to_csv("../data/results/with_ellipse.csv", index=False)
from run import Run
r = Run("../data/images1")
df = r.all_points(x=0, y=0, h=500, w=500,
plot=False, crop_included=True)
df